package com.jic.member.impl;

import java.lang.Long;
import java.math.BigDecimal;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.jic.common.base.vo.AdminOperate;
import com.jic.common.base.vo.RestResult;
import com.jic.manager.api.manage.SysDeptApi;
import com.jic.member.entity.MememberGrade;
import com.jic.member.entity.power.MegradeRule;
import com.jic.member.mapper.MememberGradeMapper;
import com.jic.member.mapper.power.MegradeRuleMapper;
import com.jic.member.request.MemberGradeRequest;
import com.jic.member.request.QueryMemLevelListByIdsRequest;
import com.jic.member.response.MemberGradeResponse;
import com.jic.member.response.MememberGradeForMarket;
import com.jic.member.response.MememberGradeResponse;
import com.jic.member.service.MememberGradeService;
import com.jic.common.base.vo.PageResult;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

/**
 * 会员等级表
 *
 * @author :
 * @version : v1.0.0
 * @email :
 * @since : 2020-04-03 02:09:28
 */
@Service
@Slf4j
public class MememberGradeServiceImpl implements MememberGradeService {

    @Resource
    private MememberGradeMapper mememberGradeMapper;
    @Resource
    MegradeRuleMapper megradeRuleMapper;

    @Resource
    private SysDeptApi sysDeptApi;



    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult<Long> insert(MemberGradeRequest mememberGrade) {
        RestResult result = new RestResult();
        long flag = 0;
        /*先判断登录账号所属层级，如果是子母平台则直接操作*/
        Integer deptType = mememberGrade.getAdminOperate().getDeptType().getCode();
        //组装插入数据
        MememberGrade mememberGrade1 = new MememberGrade();
        mememberGrade1.setCreateTime(new Date());
        mememberGrade1.setDeptId(mememberGrade.getAdminOperate().getDeptId());
        mememberGrade1.setCreatorName(mememberGrade.getAdminOperate().getOperateName());
        mememberGrade1.setDeleteFlag(0);
        mememberGrade1.setGrowRangeStart(Long.valueOf(mememberGrade.getGrowRangeStart()));
        mememberGrade1.setGrowRangeEnd(Long.valueOf(mememberGrade.getGrowRangeEnd()));
        mememberGrade1.setLevelName(mememberGrade.getLevelName());
        mememberGrade1.setYearDeduct(mememberGrade.getYearDeduct());
        //组装查询数据
        MememberGrade mememberQuery = new MememberGrade();
        mememberQuery.setGrowRangeStart(Long.valueOf(mememberGrade.getGrowRangeStart()));
        mememberQuery.setGrowRangeEnd(Long.valueOf(mememberGrade.getGrowRangeEnd()));
        mememberQuery.setDeptId(mememberGrade.getAdminOperate().getDeptId());
        mememberQuery.setDeleteFlag(0);
        if (deptType == 0) {
            //查询新增的成长值区间是否有交集
            List<MememberGrade> resultQuery = mememberGradeMapper.queryByInterval(mememberQuery);
            if (CollectionUtils.isNotEmpty(resultQuery)){
                result.setCode("9999");
                result.setMsg("等级成长值区间,不可有交集!");
                return result;
            }
            flag = mememberGradeMapper.insert(mememberGrade1);
            Long deptId = mememberGrade.getAdminOperate().getDeptId();
            MememberGrade mememberGrade2 =new MememberGrade();
            mememberGrade2.setDeleteFlag(0);
            mememberGrade2.setDeptId(mememberGrade.getAdminOperate().getDeptId());
            List<MememberGrade> query = mememberGradeMapper.query(mememberGrade2);
            //对当前组织下的所有等级 依照成长值大小进行排序
            Integer[] longs = memberSort(query);
            //修改等级levelCode
            updateLevelCode(longs,query,deptId);
        }
        result.setData(flag);
        return result;
    }

    @Override
    public RestResult<Long> delete(MemberGradeRequest mememberGrade) {
        RestResult result = new RestResult();
        MegradeRule memberGrade = new MegradeRule();
        long flag = 0;

        if (mememberGrade.getId() != null) {
            //查询子平台是否关联平台权益
            memberGrade.setDeleteFlag(0);
            memberGrade.setGradeId(mememberGrade.getId());
            List<MegradeRule> resultGrade = megradeRuleMapper.query(memberGrade);
            if (resultGrade.size() > 0) {
                result.setMsg("该等级下已关联平台权益，请解除关联后再进行操作!");
                result.setCode("9999");
                return result;
            }
            flag = mememberGradeMapper.delete(mememberGrade.getId());

        } else {
            log.error("删除失败，id为空");
        }
        result.setData(flag);


        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult<Long> update(MemberGradeRequest mememberGrade) {
        RestResult result = new RestResult();
        long flag = 0;

        if (mememberGrade != null) {
            MememberGrade mememberGrade1 = new MememberGrade();
            BeanUtils.copyProperties(mememberGrade, mememberGrade1);
            mememberGrade1.setUpdater(mememberGrade.getAdminOperate().getOperator());
            mememberGrade1.setCreatorName(mememberGrade.getAdminOperate().getOperateName());
            flag = mememberGradeMapper.update(mememberGrade1);
        } else {
            log.error("修改失败");
        }

        result.setData(flag);
        return result;
    }

    @Override
    public MememberGrade queryByPrimaryKey(Long id) {
        return mememberGradeMapper.queryByPrimaryKey(id);
    }

    @Override
    public List<MememberGrade> query(MememberGrade mememberGrade) {
        return mememberGradeMapper.query(mememberGrade);
    }



    /**
     * 为营销中心开的接口
     * 根据条件查询会员等级配置表
     * @param request 入参
     * @Author tzc
     * @return 包含MemberGradeResponse的列表；
     * @Date 2020-7-1 01:13:25
     */
    @Override
    public RestResult<List<MememberGradeForMarket>> listMememberGradeByParam(MemberGradeRequest request) {
        log.debug("【对外接口】【会员列表查询】，入参request = {}", JSON.toJSONString(request));

        if (null == request){
            return RestResult.error("1111","入参为空");
        }

        if (null == request.getDeptIds()){
            return RestResult.error("2222","平台Id字符串（多个子平台Id用逗号分隔）为空");
        }

        String deptIds = request.getDeptIds();
        String[] deptId = deptIds.split(",");

        log.debug("开始根据平台ID的数组，查询等级列表，入参request = {}", JSON.toJSONString(deptId));
        List<MememberGrade> parentGradeList = mememberGradeMapper.queryInDeptArry(deptId);
        log.debug("开始根据平台ID的数组，查询等级列表，出参个数 = {}", parentGradeList.size());

        List<MememberGradeForMarket> mememberGradeForMarketList = new ArrayList<>();
        Set<Long> deptIdSet = new HashSet<>();
        for (MememberGrade mg :parentGradeList) {
            if (!deptIdSet.contains(mg.getDeptId())) {
                deptIdSet.add(mg.getDeptId());
                MememberGradeForMarket mememberGradeForMarket = new MememberGradeForMarket();
                mememberGradeForMarket.setDeptId(mg.getDeptId());
                mememberGradeForMarketList.add(mememberGradeForMarket);
            }
        }

        for (MememberGradeForMarket item : mememberGradeForMarketList) {
            for (MememberGrade mg : parentGradeList) {
                if (mg.getDeptId().equals(item.getDeptId())) {
                    List<MememberGradeResponse> list = item.getMememberGradeResponseList();
                    if (list == null) {
                        list = new ArrayList<>();
                    }
                    MememberGradeResponse response = new MememberGradeResponse();
                    BeanUtils.copyProperties(mg, response);
                    list.add(response);
                    item.setMememberGradeResponseList(list);
                }else{
                    log.error("MememberGradeForMarket:"+item.getDeptId());
                    log.error("MememberGrade:"+mg.getDeptId());
                }
            }
        }

        return RestResult.success(mememberGradeForMarketList);
    }



    @Override
    public RestResult<PageResult<MemberGradeResponse>> queryPage(MemberGradeRequest mememberGrade) {
        // 计算下标
        int startIndex = (mememberGrade.getStart() - 1) * mememberGrade.getLimit();
        List<MemberGradeResponse> list = mememberGradeMapper.queryPage(startIndex, mememberGrade.getLimit(), mememberGrade);
        long count = mememberGradeMapper.queryPageCount(mememberGrade);
        list.forEach(items -> {
            RestResult<String> name = sysDeptApi.queryDeptNameById(items.getDeptId());
            items.setDeptName(name.getData());
        });
        PageResult pageResult = new PageResult();
        pageResult.setTotal(count);
        pageResult.setRows(list);
        RestResult result = new RestResult();
        result.setData(pageResult);
        return result;
    }


    public Integer [] memberSort (List<MememberGrade> mememberGrades){
        List<Integer>memberList = new ArrayList<>();
        mememberGrades.forEach(items->{
            BigDecimal start=new BigDecimal(items.getGrowRangeStart()==null? 0 : items.getGrowRangeStart());
            BigDecimal end=new BigDecimal(items.getGrowRangeEnd()==null? 0 : items.getGrowRangeEnd());
            memberList.add(Integer.parseInt(start.add(end).toString()));
        });
        Integer arr[] = memberList.toArray(new Integer[memberList.size()]);
        for (int i=0;i<arr.length;i++){
            for (int j=0;j<i;j++){
                if (arr[i]>arr[j]){
                    int temp;
                    temp=arr[i];
                    arr[i]=arr[j];
                    arr[j]=temp;
                }
            }
        }
        return arr;
    }

    public void updateLevelCode(Integer[] longs, List<MememberGrade> query, Long deptId){
        MememberGrade mememberGrade2 =new MememberGrade();
        mememberGrade2.setDeleteFlag(0);
        mememberGrade2.setDeptId(deptId);
        int size = query.size();
        for (int j=0;j<longs.length;j++){
            for (int i=0;i<query.size();i++){
                BigDecimal start=new BigDecimal(query.get(i).getGrowRangeStart());
                BigDecimal end=new BigDecimal(query.get(i).getGrowRangeEnd());
                BigDecimal value =new BigDecimal(longs[j]);
                if (value.equals(start.add(end))){
                    mememberGrade2.setId(query.get(i).getId());
                    mememberGrade2.setLevelCode(String.valueOf(size));
                    long update = mememberGradeMapper.update(mememberGrade2);
                    size--;
                }
            }
        }
    }


    @Override
    public RestResult<PageResult<MemberGradeResponse>> queryStorePowerList(MemberGradeRequest mememberGrade) {
        // 计算下标
        AdminOperate adminOperate = mememberGrade.getAdminOperate();
        if (adminOperate.getDeptType().getCode() == 1){
            mememberGrade.setDeptId(adminOperate.getDeptId());
        }
        int startIndex = (mememberGrade.getStart() - 1) * mememberGrade.getLimit();
        List<MemberGradeResponse> list = mememberGradeMapper.queryStoreGrade(startIndex, mememberGrade.getLimit(), mememberGrade);
        long count = mememberGradeMapper.queryStoreGradeCount(mememberGrade);
        list.forEach(items -> {
            RestResult<String> name = sysDeptApi.queryDeptNameById(items.getDeptId());
            items.setDeptName(name.getData());
        });
        PageResult pageResult = new PageResult();
        pageResult.setTotal(count);
        pageResult.setRows(list);
        RestResult result = new RestResult();
        result.setData(pageResult);
        result.setCode("0000");
        return result;
    }

    @Override
    public RestResult<PageResult<MemberGradeResponse>> queryStoreGradePage(MemberGradeRequest mememberGrade) {
        AdminOperate adminOperate = mememberGrade.getAdminOperate();
        if(adminOperate.getDeptType().getCode() == 1){
            mememberGrade.setDeptId(adminOperate.getDeptId());
        }
        // 计算下标
        int startIndex = (mememberGrade.getStart() - 1) * mememberGrade.getLimit();
        List<MemberGradeResponse> list = mememberGradeMapper.queryPage(startIndex, mememberGrade.getLimit(), mememberGrade);
        long count = mememberGradeMapper.queryPageCount(mememberGrade);
        list.forEach(items -> {
            RestResult<String> name = sysDeptApi.queryDeptNameById(items.getDeptId());
            items.setDeptName(name.getData());
        });
        PageResult pageResult = new PageResult();
        pageResult.setTotal(count);
        pageResult.setRows(list);
        RestResult result = new RestResult();
        result.setData(pageResult);
        return result;
    }

    @Override
    public RestResult<List<MememberGradeResponse>> queryMemLevelListByIds(QueryMemLevelListByIdsRequest request) {
        List<MememberGradeResponse> rest = mememberGradeMapper.queryInIds(request.getIds());
        return RestResult.success(rest);
    }
}